package group.sicher.core.exception.base;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 系统异常抽象基类
 */
public abstract class BaseException extends RuntimeException {


    public BaseException() {
    }

    public BaseException(String message) {
        super(message);
    }

    public BaseException(String message, Throwable cause) {
        super(message, cause);
    }

    public BaseException(Throwable cause) {
        super(cause != null ? cause.getMessage() : null, cause);
    }

    /**
     * 获取异常栈消息
     *
     * @return
     */
    public String getStackMessage() {
        String stackMessage = null;
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            printStackTrace(pw);

            stackMessage = sw.getBuffer().toString();
            sw.flush();
            pw.flush();
            sw.close();
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stackMessage;
    }

    public String getMessage() {
        if (super.getMessage() != null) {
            return super.getMessage();
        }
        if (this.getCause() != null) {
            return this.getCause().getMessage();
        }
        return null;
    }

    public StackTraceElement getRootStackTrace() {
        StackTraceElement[] traces = this.getStackTrace();
        if (traces.length > 0) {
            return traces[0];
        }
        return null;
    }

    /**
     * 获取异常发生类
     *
     * @return
     */
    public String getCauseClass() {
        StackTraceElement trace = this.getRootStackTrace();
        if (trace != null) {
            return trace.getClassName();
        }
        return null;
    }

    /**
     * 获取异常发生方法
     *
     * @return
     */
    public String getCauseMethod() {
        StackTraceElement trace = this.getRootStackTrace();
        if (trace != null) {
            return trace.getMethodName();
        }
        return null;
    }

    /**
     * 获取异常发生行号
     *
     * @return
     */
    public int getCauseLine() {
        StackTraceElement trace = this.getRootStackTrace();
        if (trace != null) {
            return trace.getLineNumber();
        }
        return -1;
    }
}
